package org.betasoftware.cloud;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;

import org.betasoftware.cloud.drive.DriveCloudProvider;
import org.junit.Before;
import org.junit.Test;

import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.api.services.drive.DriveScopes;

public class DriveUploadFileTrial {

	private static final String CLIENT_ID = "325634637235-lirjbigu7etk5baeh7o55kimnq1hlkor.apps.googleusercontent.com";
	private static final String CLIENT_SECRET = "-CrbsjKIccG9vBxzYQjR92x1";
	private static final String REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob";

	private static final String APPLICATION_NAME = "DriveTest";

	private GoogleCredential credential;

	private CloudFileFactory factory = new CloudFileFactory();

	@Before
	public void logonToGoogle() throws IOException {
		HttpTransport httpTransport = new NetHttpTransport();
		JsonFactory jsonFactory = new JacksonFactory();

		GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
				httpTransport, jsonFactory, CLIENT_ID, CLIENT_SECRET,
				Arrays.asList(DriveScopes.DRIVE)).setAccessType("online")
				.setApprovalPrompt("auto").build();

		String url = flow.newAuthorizationUrl().setRedirectUri(REDIRECT_URI)
				.build();
		System.out
				.println("Please open the following URL in your browser then type the authorization code:");
		System.out.println("  " + url);
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String code = br.readLine();

		GoogleTokenResponse response = flow.newTokenRequest(code)
				.setRedirectUri(REDIRECT_URI).execute();
		credential = new GoogleCredential().setFromTokenResponse(response);

		DriveCloudProvider provider = new DriveCloudProvider(APPLICATION_NAME);
		provider.setHttpTransport(httpTransport);
		provider.setJsonFactory(jsonFactory);
		provider.authorize(credential);

		factory.addProvider(provider);
	}

	@Test
	public void test() {
		CloudFile file = factory.create("drive://testfile.txt");

	}

}
